package com.ruoyi.app.controller;

import com.ruoyi.app.ali.HttpUtils;
import com.ruoyi.app.domain.User;
import com.ruoyi.app.service.IUserService;
import com.ruoyi.app.util.QiniuUtils;
import com.ruoyi.app.util.Result;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

@RequestMapping("userlogin")
@RestController
public class UserController {
    @Autowired
    IUserService iUserService;
    @Autowired
    RedisService redisService;

    @RequestMapping("login")
    public String login(@RequestBody User user) {
        User login = iUserService.getById(user.getPhone());
//        redisService.setCacheObject("用户Id", login.getId());
        return iUserService.login(user);
    }

    @RequestMapping("reight")
    public AjaxResult reight(@RequestBody User user) {
        return iUserService.reight(user);
    }

    @RequestMapping("fileUpload")
    public Result upload(MultipartFile imgFile) {
        String originalFilename = imgFile.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String s = UUID.randomUUID().toString().replaceAll("-", ".");
        String fileName = s + substring;
        try {
            QiniuUtils.upload2Qiniu(imgFile.getBytes(), "http://sw771v73v.hb-bkt.clouddn.com/" + fileName);
            return Result.ok("添加成功", "http://sw771v73v.hb-bkt.clouddn.com/" + fileName);
        } catch (IOException e) {
            return Result.error("添加失败");
        }
    }


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //发送短信
    @RequestMapping("code")
    public Result code(String phone) {
        System.err.println(phone);
        //生成随机验证码
        Random random = new Random();
        int i = random.nextInt(89999) + 10000;
        //保存验证码
        stringRedisTemplate.opsForValue().set(phone, i + "");

        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";
        String method = "POST";
        String appcode = "98307b73e0ea4d59a97884e847b666b3";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        // 手机号码
        querys.put("mobile", phone);
        // 随机数 作为验证码
        querys.put("param", "**code**:" + i + ",**minute**:5");

        //smsSignId（短信前缀）和templateId（短信模板），可登录国阳云控制台自助申请。参考文档：http://help.guoyangyun.com/Problem/Qm.html

        querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
        querys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");
        Map<String, String> bodys = new HashMap<String, String>();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从\r\n\t    \t* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java\r\n\t    \t* 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            System.err.println(1);
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok("发送成功");
    }


    //验证码验证
    @RequestMapping("check")
    public Result check(String code, String phone) {
        System.err.println(code + "+" + phone);
        //从redis获取验证码
        String c = stringRedisTemplate.opsForValue().get(phone);

        //获取不到
        if (c == null || c.length() == 0) {
            return Result.error("验证码无效，请重新生成验证码");
        }
        //获取到 - 进行比较
        if (!c.equals(code)) {
            //比较失败
            return Result.error("你输入的验证码有误，请重新输入");
        } else {
            User login = iUserService.getById(phone);
            System.err.println("登陆的人为:"+login);
            redisService.setCacheObject("用户Id", login.getId());
            
            // 返回用户信息,包含头像URL
            return Result.ok("操作成功", login);
        }
    }

    // 更新用户头像
    @PostMapping("/updateAvatar")
    public Result updateAvatar(@RequestBody Map<String, String> params) {
        String avatar = params.get("avatar");
        if (avatar == null || avatar.isEmpty()) {
            return Result.error("头像URL不能为空");
        }

        // 获取当前用户ID
        Integer userId = (Integer) redisService.getCacheObject("用户Id");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 更新用户头像
        User user = new User();
        user.setId(userId);
        user.setAvatar(avatar);
        iUserService.updateUser(user);

        return Result.ok("更新成功");
    }
}
